#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Sprites;
using UnityEngine.UI;

namespace Neatly.UI
{
    public class NRadarChart : NImageBase
    {
        //用户设置的数据
        private List<float> m_CurrentData = new List<float>();
        //图片的权重比
        public float m_Percent = 0.1f;
        
        
        public void SetRadarData(float[] data, float time = 0.5f)
        {
            UITween.RadarScale(this, data, time);
        }

        public List<float> GetCurrentList()
        {
            SetVerticesDirty();
            return m_CurrentData;
        }

        //雷达绘制
        //X = left, Y = bottom, Z = right, W = top.
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            vh.Clear();
            if (m_CurrentData == null || m_CurrentData.Count < 2) return;

            var color = (Color32) this.color;
            var rect = this.GetPixelAdjustedRect();
            var radius = rect.width > rect.height ? rect.width / 2.0f : rect.height / 2.0f;
            var center = new Vector2(0, 0);
            var count = m_CurrentData.Count;

            if (m_Sprite == null)
            {
                NDebug.LogError("Sprite is null");
                return;
            }
            var uv = DataUtility.GetOuterUV(m_Sprite);

            var centerX = uv.x + (uv.z - uv.x) * m_Percent;
            vh.AddVert(center, color, new Vector2(centerX, (uv.y + uv.w) / 2.0f));
            var angle = 360.0f / count;

            for (var i = 0; i < count; i++)
            {
                var temp = new Vector2(0, radius * m_CurrentData[i]);

                var qr = Quaternion.AngleAxis(angle * i * -1.0f, Vector3.forward);
                temp = qr * temp;
                temp += center;

                if (i % 2 == 0)
                {
                    vh.AddVert(temp, color, new Vector2(uv.x, uv.y));
                }
                else
                {
                    vh.AddVert(temp, color, new Vector2(uv.x, uv.w));
                }
            }

            for (var i = 0; i < count; i++)
            {
                var i1 = i + 1;
                var i2 = i == count - 1 ? 1 : i + 2;
                vh.AddTriangle(0, i1, i2);
            }
        }
    }
}